package com.cst.security.authentication;

import com.cst.security.baseUtils.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
@EnableResourceServer
public class CstResourceServerConfig extends ResourceServerConfigurerAdapter {

	private final static Logger logger = LoggerFactory.getLogger(CstResourceServerConfig.class);

	@Autowired
	protected AuthenticationSuccessHandler cstAuthenticationSuccessHandler;

	@Autowired
	protected AuthenticationFailureHandler cstAuthenticationFailureHandler;

	@Autowired
	private SecurityProperties securityProperties;

	@Override
	public void configure(HttpSecurity http) throws Exception {

		http
			.formLogin()//表单登录
			.loginPage("/authentication/require")//自定义登录跳转方法
			.loginProcessingUrl("/authentication/form")// 提交登录表单地址(与登录页中提交的地址一致，就可以提交到登录验证服务MyUserDetailsService 中)
	        .successHandler(cstAuthenticationSuccessHandler)//成功后跳转自定义方法
			.failureHandler(cstAuthenticationFailureHandler)//失败后跳转自定义方法
			.and()
			.httpBasic()
			.and()
			.authorizeRequests()
			.antMatchers("/authentication/require",securityProperties.getBrowser().getSignInPage()).permitAll()//这个页面不需要身份认证，其他都需要
			.anyRequest()//任何请求
			.authenticated()//都需要身份认证
			.and()
			.csrf().disable();//先禁用跨站访问功能
	}
}
